package com.liumin.publiclib.helper;

import android.content.Context;
import android.os.Process;

import androidx.annotation.NonNull;

import com.tencent.bugly.crashreport.CrashReport;

/**
 * 2019/12/24 11:48
 * 异常上报
 *
 * @author LiuWeiHao
 */
public class CrashHandler {

    /**
     * 初始化
     *
     * @param context 上下文
     * @param key     配置KEY
     * @param isDebug 是否debug模式
     */
    public static void init(Context context, String key, boolean isDebug) {
        initCrash();
        CrashReport.initCrashReport(context, key, isDebug);
    }

    /**
     * 初始化
     *
     * @param context  上下文
     * @param key      配置KEY
     * @param isDebug  是否debug模式
     * @param strategy 是否为上报进程
     */
    public static void init(Context context, String key, boolean isDebug, CrashReport.UserStrategy strategy) {
        initCrash();
        CrashReport.initCrashReport(context, key, isDebug, strategy);
    }

    private static void initCrash() {
        // 获取系统默认的UncaughtException处理器
        Thread.UncaughtExceptionHandler exceptionHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(@NonNull Thread thread, @NonNull Throwable throwable) {
                //自定义处理异常
                throwable.printStackTrace();
                try {
                    Thread.sleep(3000);
                    postCatchedException(throwable);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
                if (exceptionHandler != null) {
                    exceptionHandler.uncaughtException(thread, throwable);
                } else {
                    Process.killProcess(Process.myPid());
                    System.exit(1);
                }
            }
        });
    }

    /**
     * 上传异常信息
     *
     * @param throwable 异常
     */
    public static void postCatchedException(Throwable throwable) {
        CrashReport.postCatchedException(throwable);
    }

    /**
     * 上传异常信息
     *
     * @param throwable 异常
     */
    public static void postCatchedException(Throwable throwable, Thread thread) {
        CrashReport.postCatchedException(throwable, thread);
    }

}
